package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonFunction;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.CommonQueryMailUsedError;
import org.json.JSONObject;
/**
 * 注册通过Ajax方法调用URL：ajax_register<br>
 * 必须登陆：false<br>
 * 必须管理：false<br>
 * 参数：<br>
 * mail，必须，注册的邮箱<br>
 * name，必须，注册用户的用户名<br>
 * password，必须，注册用户的密码<br>
 * vcode，必须，图片中的验证码 {@link GetVerificationCode}<br>
 * mail_vcode，必须，验证邮箱的验证码 {@link AjaxSendMailVerificationCode}<br>
 * 注：邮箱必须没有被注册过<br>
 * @author fc
 */
public class AjaxRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		Connection connection = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			String mail = req.getParameter("mail");
			String name = req.getParameter("name");
			String password = req.getParameter("password");
			if (CommonFunction.check_mail(mail) && CommonFunction.check_name(name)
					&& CommonFunction.check_password(password)) {
				if (CommonFunction.check_vcode(req, "vcode")) {
					if (CommonFunction.check_vcode(req, "mail_vcode")) {
						connection = config.getConn();
						CommonQuery.insert_register(connection, mail, name, password);
						json.put("type", 0);
						json.put("msg", "注册成功");
					} else {
						json.put("type", -1);
						json.put("msg", "邮箱验证码错误");
					}
				} else {
					json.put("type", -2);
					json.put("msg", "图片验证码错误");
				}
			} else {
				json.put("type", -3);
				json.put("msg", "参数错误");
			}
		}catch (CommonQueryMailUsedError e) {
			json.put("type", -4);
			json.put("msg", "邮箱已被使用");
		} catch (Exception e) {
			json.put("type", -5);
			json.put("msg", "未知错误");
			Logger.getRootLogger().error(e);
		}finally {
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().error(e);
				}
			}
		}
		req.getSession().setAttribute("vcode", null);
		resp.getWriter().print(json);
	}

}
